﻿using AiMoWindows.CodeScripts;
using AiMoWindows.CodeScripts.IO;
using AiMoWindows.Localization;
using AiMoWindows.Windows.SaveCode;
namespace AiMoWindows.MainActions.ScriptActions.SubActions
{
    class OpenSaveScriptAction(ActionsController actions, ScriptManager scriptManager)
    {
        readonly ActionsController actions = actions;
        readonly ScriptManager scriptManager = scriptManager;
        // Drop 的时候，从这里打开
        public void OpenScriptWithPath(string path)
        {
            if (CodeIO.IsValidAiMoScriptFilePath(path))
            {
                CodeIO.RepairFileExtension(ref path);
                if (!Entrance.AiMoProgram.Instance.OpenNewAimoScriptForm(filePath: path, out string error))
                {
                    actions.ClearDebugPrint();
                    actions.Printer.PrintDebug(error);
                }
            }
        }
        public void OpenScript()
        {
            if (!scriptManager.PerformOpen(out string error))
            {
                actions.ClearDebugPrint();
                actions.Printer.PrintDebug(error);
            }
        }
        public async void SaveScript()
        {
            actions.ClearDebugPrint();
            if (!await actions.SyncAction.SyncScriptsWithFormat())
            {
                // 无法同步，格式有误
                return;
            }
            // 实现保存脚本的逻辑
            if (scriptManager.NotSave)
            {
                ShareSaveResult saveResult = scriptManager.ShowShareSaveInfo(SaveMode.Save);
                if (saveResult.OK)
                {
                    scriptManager.PerformSave(saveResult, out string error);
                    actions.Printer.PrintDebug(error);
                }
            }
            else
            {
                if (scriptManager.HasSavePath) actions.Printer.PrintDebug(Local.Get("Already saved in file:") + Environment.NewLine + scriptManager.SavePath);
                // else save new empty file
            }
        }

        public async void SaveAsScript()
        {
            actions.ClearDebugPrint();
            // 实现另存为脚本的逻辑
            if (!await actions.SyncAction.SyncScriptsWithFormat()) return;
            ShareSaveResult saveResult = scriptManager.ShowShareSaveInfo(SaveMode.SaveAs);
            if (saveResult.OK)
            {
                scriptManager.PerformSave(saveResult, out string error);
                actions.Printer.PrintDebug(error);
            }
        }
    }
}
